package com.example.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.api.entity.User;
import com.example.api.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *  @Author: 常占
 *  @Date: 2020/9/10 21:37
 *  @Description:
 */
@Component("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       //查询条件
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("name",username)
                .eq("deleted",0);

        User user = userService.getOne(query);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在"+username);
        }

        Collection<? extends GrantedAuthority> authorities =
                //分配权限
                Stream.of("ROLE_USER")
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());


        UserDetails userDetails = org.springframework.security.core.userdetails.User.builder()
                .username(username)
                .password(user.getPassword())
                .authorities(authorities)
                .build();
        return userDetails;
    }
}
